<template>
    <div class="dropdown" ref="dropdownRef">
        <a href="#" class="btn btn-outline my-2 dropdown-toggle " @click.prevent="toggleOpen">{{ title }}</a>
        <ul class="dropdown-menu" :style="{ display: 'block' }" v-if="isOpen">
        <slot></slot>
        </ul>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from "vue"
import useClickOutside from "@/hooks/useClickOutside"


export default defineComponent({
    props:{
        title: {
            type:String,
            required: true
        }
    },
    setup () {
        const isOpen = ref(false)
        const dropdownRef = ref<null | HTMLElement>(null)
        const toggleOpen = () => {
            isOpen.value = !isOpen.value
        }
        // const handler = (e: MouseEvent) => {
        //     if(dropdownRef.value) {
        //         if(!dropdownRef.value.contains(e.target as HTMLElement) && isOpen.value){
        //             isOpen.value = false
        //         }
        //     }
        // }
        //挂载完成后
        // onMounted(() => {
            //addEventListener添加事件
        //     document.addEventListener('click',handler)
        // })
        //组件销毁后
        // onUnmounted(() => {
            //removeEventListener移除事件
        //     document.removeEventListener('click',handler)
        // })
        const isClickOutSide = useClickOutside(dropdownRef)
        //监听isClickOutSide
        watch(isClickOutSide,() => {
            if(isOpen.value && isClickOutSide.value) {
                isOpen.value = false
            }
        })
        return{
            isOpen,
            toggleOpen,
            dropdownRef
        }
    }
})
</script>